const mysql = require('mysql');
const _conf = require('../config/db');
const _dbUtil = require('../util/db_util');
const _base = require('../util/base');
const _recommendSql = require('./recommendSqlMapping');
const async = require('async');

// 使用连接池，提升性能
const pool = mysql.createPool(_dbUtil.extend({}, _conf.mysql));

//向前台返回JSON方法的简单封装
const jsonWrite = function (res, ret) {
	if (typeof ret === 'undefined') {
		res.json({
			hasError: true,
			errMsg: '操作失败!'
		});
	} else {
		res.json(ret);
	}
};

module.exports = {
	
	// 查询系统推荐操作
	querySystemRecommendList: function (req, resp, next) {
		pool.getConnection(function (err, connection) {
			if (err) {
				console.error(err);
				return;
			}
			var params = req.params;
			//TODO 增加比对user_id和uuid的中间件
			console.error('user_id:'+params.user_id);
			console.error('uuid:'+params.uuid);
			
			// 查询文章源和标签
			let SourceAndLabel = function (callback) {
				connection.query(_recommendSql.queryArticleSourceAndLabel, [
				], function (err, result) {
					if (err) {
						console.log(err);
						callback(err, null);
						return;
					}
					console.log('查询标签和来源成功');
					let label_list = new Set();
					let art=[];
					
					for(let item of result)
					{
						art.push(_base.getSource(item));
						label_list.add(_base.getAllLabel(item));
					}
					
					art = [..._base.uniqueArr(art)];
					
					for(let item of art)
					{
						for(let label of label_list)
						{
							if(item.id === label.id){
								item.label_list.push(label.label_name);
							}
						}
					}
					callback(null,art);
				});
			};
			
			// 查询支持者
			let ArticleSupport = function (art,callback) {
				art.forEach((item,index)=>
				{
					connection.query(_recommendSql.queryArticleSupport, [
						item.id
					], function (err, result) {
						if (err) {
							console.log(err);
							callback(err, null);
							return;
						}
						let arr= [];
						for(let item of result)
						{
							let obj={};
							obj.user_id = item.id;
							obj.head_portrait = item.head_portrait;
							obj.nick_name = item.nick_name;
							obj.gender = item.gender;
							obj.birthday = item.birthday;
							obj.address = item.address;
							obj.signature = item.signature;
							arr.push(obj);
						}
						item.supportUsers = [...arr];
						
						console.log('查询段落信息:'+item.id+'成功');
						
						if(index === art.length-1)
						{
							callback(null,art);
						}
					});
				})
			};
			
			// 查询段落位置
			let ArticleParagraph = function (art,callback) {
				art.forEach((item,index)=>
				{
					connection.query(_recommendSql.queryArticleParagraph, [
						item.id
					], function (err, result) {
						if (err) {
							console.log(err);
							callback(err, null);
							return;
						}
						let arr= [];
						for(let item of result)
						{
							let obj={};
							obj.id = item.id;
							obj.location = item.location;
							arr.push(obj);
						}
						item.paragraph = [...arr];
						
						console.log('查询段落信息:'+item.id+'成功');
						
						if(index === art.length-1)
						{
							callback(null,art);
						}
					});
				})
			};
			
			// 查询段落元素关系位置
			let ArticleElementOrder = function (art,callback) {
				art.forEach((item,index)=>
				{
					let img_count = 0;
					let video_count = 0;
					for(let ele of item.paragraph)
					{
						connection.query(_recommendSql.queryArticleElementOrder, [
							ele.id
						], function (err, result) {
							if (err) {
								console.log(err);
								callback(err, null);
								return;
							}
							let img_arr= [];
							let video_arr= [];
							let text_arr= [];
							for(let item of result)
							{
								if(item.image_id)
								{
									img_count++;
									let obj={};
									obj.image_id = item.image_id;
									obj.order_number = item.order_number;
									img_arr.push(obj);
								}
								if(item.video_id)
								{
									video_count++;
									let obj={};
									obj.video_id = item.video_id;
									obj.order_number = item.order_number;
									video_arr.push(obj);
								}
								if(item.text_id)
								{
									let obj={};
									obj.text_id = item.text_id;
									obj.order_number = item.order_number;
									text_arr.push(obj);
								}
								
							}
							console.log('查询元素信息:'+item.id+'成功');
							console.error(video_count,img_count);
							// 含有视频
							if(video_count>0)
							{
								item.display_mode = 'video';
							}
							// 纯文本
							if(img_count === 0 && video_count === 0)
							{
								item.display_mode = 'text';
							}
							if(img_count>0 && img_count<3 && video_count === 0)
							{
								item.display_mode = 'single-picture';
							}
							if(img_count>= 3 && video_count === 0)
							{
								item.display_mode = 'many-picture';
							}
							ele.art_images = [...img_arr];
							ele.art_video = [...video_arr];
							ele.art_text = [...text_arr];
							
							if(index === art.length-1)
							{
								callback(null,art);
							}
						});
					}
				})
			};
			
			// 查询段落元素关系位置
			let ArticleElement = function (art,callback) {
				art.forEach((item,index)=>
				{
					for(let ele of item.paragraph)
					{
						// 查询
						for(let img of ele.art_images)
						{
							connection.query(_recommendSql.queryArticleImageElement, [
								img.image_id
							], function (err, result) {
								if (err) {
									console.log(err);
									callback(err, null);
									return;
								}
								
								img.image_url = result[0].image_url;
								
								console.error('查询图片元素信息:'+img.image_id+'成功');
								
							});
						}
							
						// 查询段落视频元素
						for(let video of ele.art_video)
						{
							connection.query(_recommendSql.queryArticleVideoElement, [
								video.video_id
							], function (err, result) {
								if (err) {
									console.log(err);
									callback(err, null);
									return;
								}
								
								video.video_url = result[0].video_url;
								
								console.error('查询视频元素信息:'+video.video_id+'成功');
								
							});
						}
							
						// 查询段落文本元素
						for(let text of ele.art_text)
						{
							connection.query(_recommendSql.queryArticleTextElement, [
								text.text_id
							], function (err, result) {
								if (err) {
									console.log(err);
									callback(err, null);
									return;
								}
								
								text.text_segment = result[0].text_segment;
								
								console.error('查询文本元素信息:'+text.text_id+'成功');
								
								if(index === art.length-1)
								{
									callback(null,art);
								}
							});
						}
					}
				})
			};
			
			async.waterfall([
				SourceAndLabel,
				ArticleSupport,
				ArticleParagraph,
				ArticleElementOrder,
				ArticleElement
			], function (err, result) {
				if (err) {
					console.log(err);
					return;
				}
				// 以json形式，把操作结果返回给前台页面
				/*let data = [...result];
				for (let item of result)
				{
					data.push(item);
				}*/
				jsonWrite(resp, result);
				//释放资源
				connection.release();
			});
			
		})
	},
};